package com.ruitaowang.show.view.api;

import com.alibaba.fastjson.JSON;
import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.account.service.WalletService;
import com.ruitaowang.core.domain.*;
import com.ruitaowang.core.utils.JwdUtils;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.CompanyService;
import com.ruitaowang.goods.service.LsMsgService;
import com.ruitaowang.goods.service.UserHistoricalTraceService;
import com.ruitaowang.goods.service.UserProfitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by neal.ma on 2017-08-01.
 */
@RestController
public class APIMsgController extends BaseController {

    @Autowired
    private LsMsgService msgService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private UserProfitService userProfitService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private UserHistoricalTraceService userHistoricalTraceService;
    @Autowired
    private LsMsgService lsMsgService;


    /**
     * @api {get} /api/wap/msgs 后台管理-互动管理-消息管理-分页获取消息列表
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/msgs
     * @apiPermission admin
     *
     * @apiName list4wap
     * @apiGroup UserMsg
     *
     * @apiParam {int} companyId 公司ID.
     * @apiParam {int} page 页数.
     * @apiParam {int} rows 每页行数.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *     "code": 0,
     *     "data": [
     *         {
     *             "companyId": 140,
     *             "ctime": 1511499678528,
     *             "fromUserAvatar": "http://wx.qlogo.cn/mmopen/OdHqM/0",
     *             "fromUserId": 4616,
     *             "fromUserText": "吕万",
     *             "luckyMoneyNum": 1,
     *             "luckyMoneyPrice": 0,
     *             "msgContent": "0",
     *             "msgId": 508,
     *             "msgType": 0,
     *             "mtime": 1511499678528,
     *             "paySn": "20171124130118528l4616",
     *             "payStatus": 0,
     *             "playMusicId": 0,
     *             "playMusicNum": 1,
     *             "playMusicPrice": 0,
     *             "playMusicText": "",
     *             "playSinger": "0",
     *             "playSingerId": 0,
     *             "pred": 9,
     *             "predText": "",
     *             "remark": "",
     *             "rewardGift": 0,
     *             "rewardGiftNum": 1,
     *             "rewardPrice": 0,
     *             "rewardText": "",
     *             "rewardTo": 0,
     *             "rstatus": 0,
     *             "toUserAvatar": "0",
     *             "toUserId": 0,
     *             "toUserText": "0",
     *             "usurpScreenNum": 1,
     *             "usurpScreenPrice": 0,
     *             "usurpScreenTableNo": 0,
     *             "usurpScreenThemeId": 0,
     *             "usurpScreenThemeText": "0",
     *             "usurpScreenTime": 0
     *         }
     *     ],
     *     "msg": "操作成功啦",
     *     "records": 45,
     *     "title": "成功",
     *     "total": 9,
     *     "type": "SUCCESS"
     *    }
     *
     * @apiError Internal Server Error.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/msgs"
     *  }
     */
    @RequestMapping(value = "/api/wap/msgs", method = RequestMethod.GET)
    public String list4wap(LsMsg msg, int page) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        msg.setPage(page);
        MsgOut o = MsgOut.success(msgService.selectForPage(msg));
        o.setRecords(msg.getRecords());
        o.setTotal(msg.getTotal());
        return this.renderJson(o);
    }
    /**
     * 获取最新的消息
     *
     * @param msgId  消息ID
     * @param companyId 公司ID
     * @return
     */
    @RequestMapping(value = "/api/wap/msgs/new", method = RequestMethod.GET)
    public String new4wap(LsMsg msg) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (ObjectUtils.isEmpty(msg.getCompanyId())||ObjectUtils.isEmpty(msg.getMsgId())) {
            return this.renderJson(MsgOut.error("缺少参数company or msg id."));
        }
        MsgOut o = MsgOut.success(msgService.select4New(msg));
        o.setRecords(msg.getRecords());
        o.setTotal(msg.getTotal());
        return this.renderJson(o);
    }
    /**
     * 发布互动消息
     * 需要参数：
     *
     * msgType 消息类型 0， 文本 1， 图片， 2 语音， 3 视频',
     * companyId 酒吧ID
     * msgContent 消息内容
     * pred 用户行为
     0 购分享
     1 我耀评
     2 我耀赞
     3 我耀秀
     4 趣竞价
     5 积分红包
     6 赏
     7 耀霸屏
     8 商家促销
     9 商家秀
     10品牌故事
     100 语音消息
     */
    @MessageMapping("/notify/hd/{companyId}")
    @SendTo("/topic/notify/hd/{companyId}")
    public String create4Common(String json, @DestinationVariable Long companyId, Principal principal
            , String userLongitude, String userLatitude) {
        //Map map = new HashMap<>();
        userLongitude = "116.491300";
        userLatitude = "39.912360";
        LOGGER.debug("principal {}", principal.getName());
        if (ObjectUtils.isEmpty(principal) || "anonymousUser".equalsIgnoreCase(principal.getName())) {
            return this.renderJson(MsgOut.error("Plz login."));
        }

        LsMsg msg = JSON.parseObject(json, LsMsg.class);
        if(msg.getPred() == 8 || msg.getPred() == 7){
            msg = msgService.selectByPK(msg.getMsgId());
            return this.renderJson(MsgOut.success(msg));
        }
        msg.setCompanyId(companyId);
        SysUser user = userService.selectByPK(msg.getFromUserId());
        if (ObjectUtils.isEmpty(msg.getCompanyId())||ObjectUtils.isEmpty(msg.getMsgType())) {
            return this.renderJson(MsgOut.error("缺少参数company id and msg type."));
        }
        update(msg, user);
//        Wallet wallet = null;
//        if(msg.getPred() == 6){//积分红包，没有奖励
//            msg.setPayStatus((byte) 1);
//            //判断用户积分数额
//            wallet = walletService.selectByPK(msg.getFromUserId());
//            if(wallet.getUserScore()<msg.getLuckyMoneyPrice()){
//                return this.renderJson(MsgOut.error("用户积分余额不足."));
//            }
//        }
        msgService.insert(msg);
        LOGGER.info("userLongitude {}", userLongitude);
        double zijiLongitude = Double.parseDouble(userLongitude); //自己的经度
        LOGGER.info("zijiLongitude {}", zijiLongitude);
        double zijiLatitude = Double.parseDouble(userLatitude);   //自己的纬度
        LOGGER.info("sendLongitude {}", msg.getLongitude());
        double sendLongitude = Double.parseDouble(msg.getLongitude());   //发送者的经度
        LOGGER.info("sendLatitude {}", msg.getLatitude());
        double sendLatitude = Double.parseDouble(msg.getLatitude());     //发送者的纬度
        double distance = JwdUtils.GetDistance(zijiLongitude, zijiLatitude, sendLongitude, sendLatitude);
        LOGGER.debug("distance {}", distance);
        String sign;
        if(distance > 1000){
            distance = distance / 1000;
            distance = Double.parseDouble(String.format("%.1f", distance));
            LOGGER.debug("distance {}", distance);
            sign = "1kmup";
        } else {
            sign = "1kmdown";
        }
        LOGGER.debug("sign {}", sign);
//        if(msg.getPred() == 6){//积分红包，没有奖励
//           msgService.faLuckyMoneySQ(msg.getMsgId());
//           //wallet -score
//           wallet.setUserScore(wallet.getUserScore()-msg.getLuckyMoneyPrice());
//           walletService.update(wallet);
//           msg.setPayStatus((byte) 0);
//           msgService.update(msg);
//        }

        return this.renderJson(MsgOut.success(msg));
    }

    /**
     * 周年祝福
     * @param json
     * @param companyId
     * @param principal
     * @return
     */
    @MessageMapping("/notify/blessing/{companyId}")
    @SendTo("/topic/notify/blessing/{companyId}")
    public String create(String json, @DestinationVariable Long companyId, Principal principal) {
        LOGGER.debug("principal {}", principal.getName());
        if (ObjectUtils.isEmpty(principal) || "anonymousUser".equalsIgnoreCase(principal.getName())) {
            return this.renderJson(MsgOut.error("Plz login."));
        }

        LsMsg msg = JSON.parseObject(json, LsMsg.class);
        Long userId = msg.getFromUserId();
        if(msg.getPred() == 16 && companyId == 0){
                msg.setFromUserId(userId);
                lsMsgService.insert(msg);
        }

        return this.renderJson(MsgOut.success(msg));
    }

    @RequestMapping("/api/wap/msgs/hd/{companyId}")
    public String create4Common4BaAndShang(LsMsg msg, @PathVariable Long companyId) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        user = userService.selectByPK(msg.getFromUserId());
        if (ObjectUtils.isEmpty(msg.getCompanyId())||ObjectUtils.isEmpty(msg.getMsgType())) {
            return this.renderJson(MsgOut.error("缺少参数company id and msg type."));
        }
        update(msg, user);
        msg.setPayStatus((byte) 1); //TODO:1 未支付
        msgService.insert(msg);
        return this.renderJson(MsgOut.success(msg));
    }

    /**
     * 拆红包（积分红包）
     * @return
     */
    @RequestMapping("/api/wap/msgs/luckyMoney/{msgId}")
    public String chaiLuckyMoney(@PathVariable Long msgId) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Map map = new HashMap();
        LsMsg msg = msgService.selectByPK(msgId);
        if (ObjectUtils.isEmpty(msg)) {
            return this.renderJson(MsgOut.error());
        }
        //如果有剩余红包，抽红包,红包放在redis中
        int money = msgService.chaiLuckyMoney(msgId, user.getId());
        if(money > 0){
            walletService.createUserProfitForScore(user.getId(), money);
        }
        List<UserProfit> userProfits = userProfitService.selectByPaySN(msg.getPaySn());
        List<SysUser> users = new ArrayList<>(msg.getLuckyMoneyNum());
        if(!ObjectUtils.isEmpty(userProfits)){
            userProfits.forEach(item->{
                SysUser user1 = userService.selectByPK(item.getUserId());
                user1.setCtime(item.getCtime());
                user1.setRemark(item.getUserProfit().toString());
                users.add(user1);
            });
        }
        SysUser sysUser = userService.selectByPK(user.getId());
        UserProfit userProfit = new UserProfit();
        userProfit.setOrderId(msgId);
        userProfit.setUserId(user.getId());
        userProfit.setOrderType((byte)19);
        List<UserProfit> userProfitList = userProfitService.select(userProfit);
        map.put("me",sysUser);//个人基本信息
        if (ObjectUtils.isEmpty(userProfitList)) {
            map.put("money",0);//个人领取红包金钱
        } else {
            map.put("money",userProfitList.get(0).getUserProfit());//个人领取红包金钱
//            map.put("money",money);//个人领取红包金钱
        }
        map.put("users",users);//所有领取信息
        map.put("hbCount",msg.getLuckyMoneyNum());//红包个数
        if (ObjectUtils.isEmpty(msg.getLuckyMoneyName())) {
            map.put("hbName","恭喜发财，大吉大利");
        } else {
            map.put("hbName",msg.getLuckyMoneyName());
        }

        //返回抽到红包的用户列表
        return this.renderJson(MsgOut.success(map));
    }

    @RequestMapping("/api/wap/msgs/openLuckyMoney/{msgId}")
    public String openLuckyMoney(@PathVariable Long msgId) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Map map = new HashMap();
        LsMsg msg = msgService.selectByPK(msgId);
        if (ObjectUtils.isEmpty(msg)) {
            return this.renderJson(MsgOut.error());
        }
        SysUser sysUser = userService.selectByPK(user.getId());
        Company company = companyService.selectByPK(msg.getCompanyId());
        map.put("headimgurl",sysUser.getHeadimgurl());
        map.put("companyName",company.getCompanyName());
        if (ObjectUtils.isEmpty(msg.getLuckyMoneyName())) {
            map.put("hbName","恭喜发财，大吉大利");
        } else {
            map.put("hbName",msg.getLuckyMoneyName());
        }
        //如果有剩余红包，抽红包,红包放在redis中
        int money = msgService.selectyMoney(msgId, user.getId());
        if(money == 0){
            map.put("havahb","0");
        } else {
            map.put("havahb","1");
        }

//        int lingHb = msgService.lingHb(msgId, user.getId());

        if(money == 2){
            map.put("lingHb","1");
        } else {
            map.put("lingHb","0");
        }

        map.put("userName",sysUser.getNickname());
        map.put("headImgUrl",sysUser.getHeadimgurl());
        UserProfit where = new UserProfit();
        where.setOrderSn(msg.getPaySn());
        where.setOrderType((byte) 19);
        where.setUserId(user.getId());
        List<UserProfit> myQiang = userProfitService.select(where);

        if(!ObjectUtils.isEmpty(myQiang)){
            map.put("lingMoney",myQiang.get(0).getUserProfit());
        } else {
            map.put("lingMoney",0);
        }

        return this.renderJson(MsgOut.success(map));
    }


    /**
     * 霸屏消息
     * 需要参数：
     * msgType 消息类型 0， 文本 1， 图片， 2 语音， 3 视频',
     * msgContent 消息内容
     * companyId 酒吧ID
     * toUserId  接收者
     * usurpScreenNum 几连霸屏
     * usurpScreenThemeId 霸屏主题编码
     * usurpScreenThemeText 霸屏主题说明
     * usurpScreenTime 霸屏时长
     * usurpScreenPrice 霸屏单价
     * usurpScreenTableNo 霸屏桌号
     * @return
     */
    @RequestMapping(value = "/api/wap/msgs/baping/create", method = RequestMethod.POST)
    public String create4Baping(LsMsg msg) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (ObjectUtils.isEmpty(msg.getCompanyId())||ObjectUtils.isEmpty(msg.getMsgType())) {
            return this.renderJson(MsgOut.error("缺少参数company id and msg type."));
        }
        update(msg, user);
        switch (msg.getMsgType()){
            case 0:
                msgService.insertText4Baping(msg);
                break;
            case 1:
                msgService.insertPhoto4Baping(msg);
                break;
            case 3:
                msgService.insertVideo4Baping(msg);
                break;
            default:
                return this.renderJson(MsgOut.error("参数不合法【msgType】"));
        }
        MsgOut o = MsgOut.success(msg);
        return this.renderJson(o);
    }
    /**
     * 打赏消息 打赏乐队
     * 需要参数：
     * companyId 酒吧ID
     * rewardTo 打赏乐队编码
     * rewardGift 打赏礼物
     * rewardPrice 打赏礼物单价
     * rewardText 打赏说明（乐队名）
     * rewardGiftNum 打赏礼物数量
     * @return
     */
    @RequestMapping(value = "/api/wap/msgs/dashang/create", method = RequestMethod.POST)
    public String create4Dashang(LsMsg msg) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (ObjectUtils.isEmpty(msg.getCompanyId())) {
            return this.renderJson(MsgOut.error("缺少参数company id."));
        }
        update(msg, user);
        msgService.insertDashang(msg);
        MsgOut o = MsgOut.success(msg);
        return this.renderJson(o);
    }
    /**
     * 点播
     * 需要参数：
     * msgType 消息类型 0， 文本 1， 图片， 2 语音， 3 视频',
     * msgContent 消息内容
     * companyId 酒吧ID
     * playSinger 点播乐队或歌手名
     * playSingerId 点播乐队或歌手ID
     * playMusicId 音乐编码
     * playMusicText 音乐名
     * playMusicPrice 点播音乐单价
     * @return
     */
    @RequestMapping(value = "/api/wap/msgs/dianbo/create", method = RequestMethod.POST)
    public String create4Dianbo(LsMsg msg) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (ObjectUtils.isEmpty(msg.getCompanyId())||ObjectUtils.isEmpty(msg.getMsgType())) {
            return this.renderJson(MsgOut.error("缺少参数company id and msg type."));
        }
        update(msg, user);
        switch (msg.getMsgType()){
            case 0:
                msgService.insertText4Dianbo(msg);
                break;
            case 1:
                msgService.insertPhoto4Dianbo(msg);
                break;
            case 3:
                msgService.insertVideo4Dianbo(msg);
                break;
            default:
                return this.renderJson(MsgOut.error("参数不合法【msgType】"));
        }
        MsgOut o = MsgOut.success(msg);
        return this.renderJson(o);
    }
    /**
     * 红包
     * 需要参数：
     * msgType 消息类型 0， 文本 1， 图片， 2 语音， 3 视频,
     * msgContent 消息内容
     * companyId 酒吧ID
     * luckyMoneyPrice 红包金额
     * luckyMoneyNum 红包数量
     * @return
     */
    @RequestMapping(value = "/api/wap/msgs/hongbao/create", method = RequestMethod.POST)
    public String create4Hongbao(LsMsg msg) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (ObjectUtils.isEmpty(msg.getCompanyId())||ObjectUtils.isEmpty(msg.getMsgType())) {
            return this.renderJson(MsgOut.error("缺少参数company id and msg type."));
        }
        update(msg, user);
        switch (msg.getMsgType()){
            case 0:
                msgService.insertText4Hongbao(msg);
                break;
            default:
                return this.renderJson(MsgOut.error("参数不合法【msgType】"));
        }
        MsgOut o = MsgOut.success(msg);
        return this.renderJson(o);
    }

    private void update(LsMsg lsMsg, SysUser from){
        lsMsg.setFromUserId(from.getId());
        lsMsg.setFromUserText(from.getNickname());
        lsMsg.setFromUserAvatar(from.getHeadimgurl());
        if(ObjectUtils.isEmpty(lsMsg.getToUserId()) || lsMsg.getToUserId() == 0){
            return;
        }
        SysUser to  = userService.selectByPK(lsMsg.getToUserId());
        lsMsg.setToUserText(to.getNickname());
        lsMsg.setToUserAvatar(to.getHeadimgurl());
        if(ObjectUtils.isEmpty(lsMsg.getMsgId())){
            return;
        }
        msgService.update(lsMsg);
    }
//
//    /**
//     * FromUserText 姓名
//     * MsgContent 祝福语
//     * LuckyMoneyNum 电话号码
//     * @param lsMsg
//     * @return
//     */
//    @RequestMapping(value = "/api/wap/msgs/zn/create", method = RequestMethod.POST)
//    public String createZN(LsMsg lsMsg){
//        SysUser user = LYSecurityUtil.currentSysUser();
//        if (ObjectUtils.isEmpty(user)) {
//            return this.renderJson(MsgOut.error("Plz login."));
//        }
//        if (ObjectUtils.isEmpty(lsMsg)) {
//            return this.renderJson(MsgOut.error("参数错误"));
//        }
//        lsMsg.setPred((byte)16);
//        lsMsg.setFromUserId(user.getId());
//        msgService.insert(lsMsg);
//        MsgOut o = MsgOut.success(lsMsg);
//        return  this.renderJson(o);
//    }
    @RequestMapping(value = "/api/wap/msgs/zn/get", method = RequestMethod.GET)
    public String getZN(LsMsg msg,int page){
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        msg.setPage(page);
        msg.setPred((byte)16);
        List<LsMsg> lsMsgs=msgService.selectForPage(msg);
        MsgOut o = MsgOut.success(lsMsgs);
        o.setRecords(msg.getRecords());
        o.setTotal(msg.getTotal());
        return  this.renderJson(o);
    }
}

